package com.xx.jicheng.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yihang.common.spring.JsonModel;

import com.xx.jicheng.entity.Account;
import com.xx.jicheng.service.AccountService;
import com.xx.jicheng.service.ConfigService;
import com.xx.jicheng.service.SmsService;

@Controller
public class RegisterController {

	@Autowired
	private AccountService accountService;

	@Autowired
	private SmsService smsService;

	@RequestMapping("/register")
	public String register() {
		return "/register";
	}

	@RequestMapping("/register/checkAccountExists")
	@ResponseBody
	public Map<String, Object> checkAccountExists(String account, JsonModel json) {
		boolean exists = accountService.checkAccountExists(account);
		json.add("accountExists", exists);
		return json.asMap();
	}

	@RequestMapping("/register/checkCellphoneExists")
	@ResponseBody
	public Map<String, Object> checkCellphoneExists(String cellphone, JsonModel json) {
		boolean exists = accountService.checkCellphoneExists(cellphone);
		json.add("cellphoneExists", exists);
		return json.asMap();
	}

	@RequestMapping("/register/sendSmsCode")
	@ResponseBody
	public Map<String, Object> sendSmsCode(String account, String cellphone, JsonModel json) {
		smsService.generateSmsCode(account, cellphone);
		return json.asMap();
	}

	@RequestMapping("/register/validateSmsCode")
	@ResponseBody
	public Map<String, Object> validateSmsCode(String cellphone, String vercode, JsonModel json) {
		boolean isValid = smsService.validateSmsCode(cellphone, vercode);
		json.add("isValid", isValid);
		return json.asMap();
	}

	@RequestMapping("/register/new")
	@ResponseBody
	public Map<String, Object> registerNew(@Valid Account account, BindingResult result, String vercode,
			JsonModel json, HttpSession session) {
		List<FieldError> errors = result.getFieldErrors();
		for (FieldError e : errors) {
			throw new RuntimeException(e.getDefaultMessage());
		}
		if (accountService.checkAccountExists(account.getAccountNo())) {
			throw new RuntimeException("用户账号已存在！");
		}
		if (accountService.checkCellphoneExists(account.getCellphone())) {
			throw new RuntimeException("手机号已注册！");
		}
		if (!smsService.validateSmsCode(account.getCellphone(), vercode)) {
			throw new RuntimeException("验证码不正确或已过期！");
		}
		accountService.register(account);
		smsService.clearSmsCode(account.getCellphone());
		session.setAttribute(ConfigService.ACCOUNT_LOGIN, account);
		return json.asMap();
	}

}
